// 不再需要 useLatest
import { useState, useRef } from "react";

// 初始模拟发布者数据
const initialPublishers = [
  { id: 1, username: "神秘资源狂人", level: 5, avatar: null },
  { id: 2, username: "资源达人", level: 4, avatar: null },
  { id: 3, username: "稀有资源猎手", level: 6, avatar: null },
  { id: 4, username: "收藏控", level: 3, avatar: null },
  { id: 5, username: "魔力王者", level: 7, avatar: null },
];

// 初始模拟提交者数据
const initialSubmitters = [
  { id: 10, username: "热心用户", level: 3, avatar: null },
  { id: 11, username: "分享达人", level: 4, avatar: null },
  { id: 12, username: "路过看看", level: 2, avatar: null },
  { id: 13, username: "资源搬运工", level: 5, avatar: null },
  { id: 14, username: "潜水员", level: 1, avatar: null },
];

// 初始模拟悬赏数据（合并列表和详情）
const initialBounties = [
  {
    id: 1,
    title: "寻找稀有音乐会现场录音资源 - 莫扎特钢琴协奏曲全集",
    description:
      "寻找莫扎特钢琴协奏曲的稀有现场录音，要求音质清晰，最好是无损格式。我收集了大部分常见版本，但仍有几场重要音乐会的录音缺失，特别是1974年伦敦皇家音乐厅的那场。\n\n我已收集的版本有：\n1. 1967年维也纳爱乐乐团版本\n2. 1982年柏林爱乐乐团版本\n3. 1995年萨尔茨堡音乐节版本\n\n特别寻找：\n1. 1974年伦敦皇家音乐厅版本（指挥：卡尔·伯姆）\n2. 1978年卡内基音乐厅版本（钢琴：穆雷·佩拉希亚）\n3. 任何由玛莎·阿格里奇演奏的现场版本\n\n格式要求：FLAC或WAV等无损格式优先，高比特率MP3也可接受。",
    reward: 2500,
    status: "active",
    publisher: initialPublishers[0],
    createdAt: "2023-12-18T08:24:30Z",
    submissions: [
      {
        id: 101,
        submitter: initialSubmitters[0],
        status: "pending",
        description:
          "我有1978年卡内基音乐厅版本的录音，是从一位收藏家那里获得的稀有资源。音质相当不错，是320kbps的MP3格式。",
        resourceLink: "https://example.com/shared/mozart_carnegie_1978.zip",
        fileUrl: null,
        createdAt: "2024-02-20T14:35:22Z",
      },
      {
        id: 102,
        submitter: initialSubmitters[1],
        status: "rejected",
        description:
          "找到了一份1974年伦敦皇家音乐厅的录音，但音质一般，有不少杂音。仅供参考。",
        resourceLink: null,
        fileUrl: "https://example.com/files/london_royal_1974_mozart.rar",
        createdAt: "2024-02-15T09:12:40Z",
      },
      {
        id: 103,
        submitter: initialSubmitters[2],
        status: "accepted",
        description:
          "我有玛莎·阿格里奇1980年在巴黎演奏的现场录音，是FLAC无损格式，音质极佳。这是私人收藏，非常稀有。",
        resourceLink:
          "https://example.com/shared/argerich_mozart_paris_1980.flac",
        fileUrl: null,
        createdAt: "2024-02-18T16:50:15Z",
      },
    ],
    submissionCount: 3,
  },
  {
    id: 2,
    title: "求70年代香港经典电影《小街》完整无删减版",
    description:
      "一直在寻找70年代香港经典电影《小街》的完整无删减版本，目前市面上流通的都是删减版，缺少约20分钟的重要情节，非常影响对电影的理解和欣赏。如果有人能提供完整版本，愿意支付相应魔力值。",
    reward: 3800,
    status: "completed",
    publisher: initialPublishers[1],
    createdAt: "2023-11-05T14:45:12Z",
    submissions: [],
    submissionCount: 5,
  },
  {
    id: 3,
    title: "寻找计算机科学经典教材《算法导论》第四版中文注释版",
    description:
      "急需《算法导论》第四版的中文注释版，最好有详细的习题解答。自学算法，但英文版看起来有些吃力，希望能找到有详细中文注释的版本，更容易理解一些复杂的算法概念。",
    reward: 1000,
    status: "active",
    publisher: initialPublishers[2],
    createdAt: "2024-01-25T09:12:48Z",
    submissions: [],
    submissionCount: 1,
  },
  {
    id: 4,
    title: "求2000年-2010年间冷门日剧合集",
    description:
      "寻找2000年到2010年间播出的冷门日剧资源，特别是那些收视率不高但口碑很好的作品。已经收集了大部分热门作品，希望能补完一些被低估的优秀作品。要求清晰度至少720p，最好带中文字幕。",
    reward: 1800,
    status: "expired",
    publisher: initialPublishers[3],
    createdAt: "2023-09-30T16:20:15Z",
    submissions: [],
    submissionCount: 0,
  },
  {
    id: 5,
    title: "求《星际迷航》全系列4K修复蓝光原盘",
    description:
      "寻找《星际迷航》系列电影和电视剧的4K修复蓝光原盘资源，需要完整的全系列，包括所有电影和各代电视剧。最好是未压缩的原盘资源，以保证最佳的观影体验。\n\n具体需要的内容包括：\n\n1. 《星际迷航：原初系列》全3季（1966-1969）4K修复版\n2. 《星际迷航》电影系列（1-13部）蓝光原盘\n3. 《星际迷航：下一代》全7季 4K修复版\n4. 《星际迷航：深空九号》全7季\n5. 《星际迷航：航海家号》全7季\n6. 《星际迷航：进取号》全4季\n7. 《星际迷航：发现号》全系列\n\n格式要求：原盘ISO或完整文件夹结构，不接受重编码版本。",
    reward: 5000,
    status: "active",
    publisher: initialPublishers[4],
    createdAt: "2024-02-10T11:35:27Z",
    submissions: [
      {
        id: 201,
        submitter: initialSubmitters[3],
        status: "pending",
        description:
          "我有《星际迷航》1-6部电影的4K蓝光原盘ISO文件，以及《原初系列》全3季的4K修复版。文件较大，总共约500GB，已上传到私人网盘。",
        resourceLink: "https://example.com/shared/startrek_4k_collection.html",
        fileUrl: null,
        createdAt: "2024-02-25T10:20:18Z",
      },
      {
        id: 202,
        submitter: initialSubmitters[4],
        status: "pending",
        description:
          "我收集了《星际迷航：下一代》全7季的4K修复版，以及《深空九号》前4季的高清版本。都是原盘结构，未经压缩。",
        resourceLink:
          "https://example.com/shared/startrek_tng_ds9_collection.html",
        fileUrl: null,
        createdAt: "2024-02-28T14:45:30Z",
      },
    ],
    submissionCount: 2,
  },
  {
    id: 6,
    title: "求宫崎骏早期作品合集（1979-1985）",
    description:
      "收集宫崎骏早期的一些作品，特别是1979-1985年间的动画作品，包括电影和短片。需要高清晰度版本，带日语原声和中文字幕。",
    reward: 2200,
    status: "active",
    publisher: initialPublishers[0],
    createdAt: "2024-02-15T08:50:33Z",
    submissions: [],
    submissionCount: 4,
  },
  {
    id: 7,
    title: "求美国摇滚乐队Guns N' Roses未发行演唱会录像",
    description:
      "寻找Guns N' Roses乐队1991-1993年间的未正式发行演唱会录像，特别是亚洲巡演部分。据说有些粉丝自己录制的内容画质还不错，但市面上很难找到完整版本。",
    reward: 3000,
    status: "active",
    publisher: initialPublishers[2],
    createdAt: "2024-01-05T19:15:40Z",
    submissions: [],
    submissionCount: 1,
  },
  {
    id: 8,
    title: "求稀有编程语言教程资源（Haskell、Erlang、OCaml）",
    description:
      "寻找函数式编程语言Haskell、Erlang和OCaml的完整教程资源，包括视频课程、电子书和实例代码。市面上对这些语言的优质中文教程很少，希望能找到深入浅出的学习资料。",
    reward: 1500,
    status: "completed",
    publisher: initialPublishers[1],
    createdAt: "2023-10-12T13:28:55Z",
    submissions: [],
    submissionCount: 6,
  },
];

// 模拟网络延迟的函数
// const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 主Hook函数
export const useBountyMock = () => {
  // 状态管理
  const [bounties, setBounties] = useState(initialBounties);
  const [currentUser, setCurrentUser] = useState(initialPublishers[0]); // 假设当前用户是第一个发布者

  // 使用 ref 来获取最新状态
  const bountiesRef = useRef(bounties);
  // 更新 ref 值以保持最新
  bountiesRef.current = bounties;

  console.log("bountiesRef", bounties, bountiesRef.current);

  // 生成唯一ID的辅助函数
  const generateId = () => Date.now();

  // 获取悬赏列表（支持分页、筛选和排序）
  const getBountyList = (params = {}) => {
    const { page = 1, size = 10, status, sort } = params;
    // 使用 ref 获取最新状态
    const currentBounties = bountiesRef.current;
    let filteredList = currentBounties.map((bounty) => ({
      id: bounty.id,
      title: bounty.title,
      description: bounty.description.split("\n")[0], // 只取描述的第一段
      reward: bounty.reward,
      status: bounty.status,
      publisher: bounty.publisher,
      createdAt: bounty.createdAt,
      submissions: bounty.submissionCount,
    }));

    // 状态筛选
    if (status && status !== "all") {
      filteredList = filteredList.filter((item) => item.status === status);
    }

    // 排序
    if (sort) {
      switch (sort) {
        case "newest":
          filteredList.sort(
            (a, b) => new Date(b.createdAt) - new Date(a.createdAt)
          );
          break;
        case "reward_desc":
          filteredList.sort((a, b) => b.reward - a.reward);
          break;
        case "reward_asc":
          filteredList.sort((a, b) => a.reward - b.reward);
          break;
        default:
          break;
      }
    }

    // 分页
    const startIndex = (page - 1) * size;
    const endIndex = startIndex + size;
    const pagedList = filteredList.slice(startIndex, endIndex);

    return {
      data: {
        list: pagedList,
        total: filteredList.length,
      },
    };
  };

  // 获取悬赏详情
  const getBountyDetail = (id) => {
    // console.log("getBountyDetail", bountiesRef.current);
    const bounty = bountiesRef.current.find((b) => b.id === parseInt(id));
    return { data: bounty || null };
  };

  // 创建悬赏任务
  const createBounty = (data) => {
    const newId = generateId();
    const newBounty = {
      id: newId,
      ...data,
      status: "active",
      publisher: currentUser,
      createdAt: new Date().toISOString(),
      submissions: [],
      submissionCount: 0,
    };

    // 更新悬赏数组
    setBounties((prev) => [newBounty, ...prev]);

    // 返回新创建的悬赏
    return { data: newBounty };
  };

  // 提交悬赏资源
  const submitBountyResource = (bountyId, data) => {
    const submissionId = generateId();
    const newSubmission = {
      id: submissionId,
      submitter:
        initialSubmitters[Math.floor(Math.random() * initialSubmitters.length)], // 随机选择一个提交者
      status: "pending",
      description: data.description || "",
      resourceLink: data.resourceLink || null,
      fileUrl: data.fileUrl || null,
      createdAt: new Date().toISOString(),
    };

    // 更新悬赏
    setBounties((prev) => {
      const updatedBounties = prev.map((bounty) => {
        if (bounty.id === parseInt(bountyId)) {
          return {
            ...bounty,
            submissions: [...bounty.submissions, newSubmission],
            submissionCount: bounty.submissionCount + 1,
          };
        }
        return bounty;
      });
      return updatedBounties;
    });

    return { data: { success: true, submission: newSubmission } };
  };

  // 关闭悬赏任务
  const closeBounty = (bountyId) => {
    // 更新状态
    setBounties((prev) =>
      prev.map((bounty) =>
        bounty.id === parseInt(bountyId)
          ? { ...bounty, status: "completed" }
          : bounty
      )
    );

    return { data: { success: true } };
  };

  // 采纳提交
  const acceptSubmission = (bountyId, submissionId) => {
    // 更新状态
    setBounties((prev) =>
      prev.map((bounty) => {
        if (bounty.id === parseInt(bountyId)) {
          const updatedSubmissions = bounty.submissions.map((submission) =>
            submission.id === submissionId
              ? { ...submission, status: "accepted" }
              : {
                  ...submission,
                  status:
                    submission.status === "accepted"
                      ? "rejected"
                      : submission.status,
                }
          );

          return {
            ...bounty,
            submissions: updatedSubmissions,
            status: "completed", // 采纳后任务自动完成
          };
        }
        return bounty;
      })
    );

    return { data: { success: true } };
  };

  // 驳回提交
  const rejectSubmission = (bountyId, submissionId) => {
    // 更新状态
    setBounties((prev) =>
      prev.map((bounty) => {
        if (bounty.id === parseInt(bountyId)) {
          const updatedSubmissions = bounty.submissions.map((submission) =>
            submission.id === submissionId
              ? { ...submission, status: "rejected" }
              : submission
          );

          return {
            ...bounty,
            submissions: updatedSubmissions,
          };
        }
        return bounty;
      })
    );

    return { data: { success: true } };
  };

  // 删除悬赏任务
  const deleteBounty = (bountyId) => {
    // 从数组中删除
    setBounties((prev) =>
      prev.filter((bounty) => bounty.id !== parseInt(bountyId))
    );

    return { data: { success: true } };
  };

  // 设置当前用户
  const setUser = (userId) => {
    const user =
      initialPublishers.find((p) => p.id === userId) || initialPublishers[0];
    setCurrentUser(user);
  };

  // 返回所有API和状态
  return {
    // 数据状态
    bounties,
    bountyList: bounties.map((bounty) => ({
      id: bounty.id,
      title: bounty.title,
      description: bounty.description.split("\n")[0], // 只取描述的第一段
      reward: bounty.reward,
      status: bounty.status,
      publisher: bounty.publisher,
      createdAt: bounty.createdAt,
      submissions: bounty.submissionCount,
    })),
    bountyDetails: bounties.reduce((acc, bounty) => {
      acc[bounty.id] = bounty;
      return acc;
    }, {}),
    currentUser,

    // API方法
    getBountyList,
    getBountyDetail,
    createBounty,
    submitBountyResource,
    closeBounty,
    acceptSubmission,
    rejectSubmission,
    deleteBounty,
    setUser,
  };
};

// 创建一个上下文Provider
export default useBountyMock;
